﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace YuQueSdk
{
    /// <summary>
    /// 网络请求帮助类
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="token">语雀个人设置的token</param>
        /// <param name="userAgent">语雀需要收集的用户标识</param>
        /// <returns>请求到的数据</returns>
        public static string HttpGet(string url, string token, string userAgent = "netCoreSdk")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Headers.Add("User-Agent", HttpUtility.UrlEncode(userAgent));
            request.Headers.Add("X-Auth-Token", HttpUtility.UrlEncode(token));

            using HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

            return reader.ReadToEnd();
        }

        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="token">语雀个人设置的token</param>
        /// <param name="userAgent">语雀需要收集的用户标识</param>
        /// <returns>请求到的数据</returns>
        public static async Task<string> HttpGetAsync(string url, string token, string userAgent = "netCoreSdk")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Headers.Add("User-Agent", HttpUtility.UrlEncode(userAgent));
            request.Headers.Add("X-Auth-Token", HttpUtility.UrlEncode(token));

            using HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

            return await reader.ReadToEndAsync();
        }
    }
}
